//
//  SkinAnalysisViewController.swift
//  月升
//
//  Created by 拉利法 on 2024/7/10.
//  皮肤分析

import UIKit

class SkinAnalysisViewController: QIBaseViewController {
    
    var img = UIImage()
    /// 原图在本地服务器地址
    var originalImgUrl = ""
    var raw_file_path = ""
    var event_name = ""
    
    private var imgPreviewView = UIImageView()
    private var selectItemBtn = UIButton()
    private var scrollView = UIScrollView()
    private var explainL = YYLabel()
    private var imgArr = [String]()
    var resultModel = QISkinAnalysisResultsModel()
    /// 美妆推荐
    let beautyRecommendCtl = BeautyRecommendViewController()
    /// 五官检测结果
//    var wuGuanModel = QIFiveSensesResultModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "皮肤分析"
  
        addUI()
        getBeautyRecommend()
    }
    
    
    private func addUI() {
        showGradientColor()
        
        imgPreviewView = UIImageView().then {
            $0.frame = CGRect(x: 15, y: NAV_HEIGHT, width: SCREEN_WIDTH - 30, height: 410)
            $0.image = img
            $0.tag = 11
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
            $0.addRoundedCorners(withRadius: 10)
        }
        view.addSubview(imgPreviewView)
        
        
        let headerView = UIView()
        headerView.frame = CGRect(x: 15, y: imgPreviewView.bottom + 10, width: SCREEN_WIDTH - 30, height: 50)
        headerView.backgroundColor = .white
        headerView.addRoundedCorners(withRadius: 10, byRoundingCorners: [.topLeft, .topRight])
        view.addSubview(headerView)
        
        let itemView = UIView()
        itemView.frame = CGRect(x: 15, y: 10, width: 180, height: 30)
        itemView.backgroundColor = ColorWithStr("#FFDCE0")
        itemView.addRoundedCorners(withRadius: 15)
        headerView.addSubview(itemView)
        
        let titleArr = ["粉刺", "毛孔", "皱纹"]
        for (index, titleStr) in titleArr.enumerated() {
            let itemBtn = UIButton().then {
                $0.frame = CGRect(x: index * 60, y: 0, width: 60, height: 30)
                $0.tag = index
                $0.titleLabel?.font = FONT(ofSize: 14)
                $0.setTitle(titleStr, for: .normal)
                $0.setTitleColor(MainColor, for: .normal)
                $0.setTitleColor(.white, for: .selected)
                $0.addRoundedCorners(withRadius: 15)
            }
            itemView.addSubview(itemBtn)
            if titleStr == "粉刺" {
                selectItemBtn = itemBtn
                selectItemBtn.isSelected = true
                selectItemBtn.backgroundColor = MainColor
                itemBtn.addTarget(self, action: #selector(acneBtnClick(btn:)), for: .touchUpInside)
            } else if titleStr == "毛孔" {
                itemBtn.addTarget(self, action: #selector(poreBtnClick(btn:)), for: .touchUpInside)
            } else if titleStr == "皱纹" {
                itemBtn.addTarget(self, action: #selector(wrinkleBtnClick(btn:)), for: .touchUpInside)
            }
        }
        
        let productsBtn = UIButton().then {
            $0.frame = CGRect(x: headerView.width - 100, y: 10, width: 90, height: 30)
            $0.backgroundColor = ColorWithStr("#FA709E")
            $0.titleLabel?.font = FONT(ofSize: 14)
            $0.setTitle("相关产品", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 15)
            $0.addTarget(self, action: #selector(productsBtnClick), for: .touchUpInside)
        }
        headerView.addSubview(productsBtn)
        
        let scrollBGView = UIView()
        scrollBGView.frame =  CGRect(x: 15, y: headerView.bottom, width: SCREEN_WIDTH - 30, height: SCREEN_HEIGHT - headerView.bottom - 50)
        scrollBGView.backgroundColor = .white
        scrollBGView.addRoundedCorners(withRadius: 10, byRoundingCorners: [.bottomLeft, .bottomRight])
        view.addSubview(scrollBGView)
        
        scrollView = UIScrollView(frame: scrollBGView.bounds)
        scrollView.backgroundColor = .white
        scrollBGView.addSubview(scrollView)
        
        explainL = YYLabel().then({
            $0.frame = CGRect(x: 15, y: 5, width: scrollView.width - 30, height: 200)
            $0.backgroundColor = .clear
//            $0.textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
            $0.numberOfLines = 0
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
            $0.addRoundedCorners(withRadius: 10)
        })
        scrollView.addSubview(explainL)
        
        
        
        let recommendBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 50, y: scrollBGView.bottom + 8, width: 100, height: 22)
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("美妆推荐", for: .normal)
            $0.setTitleColor(Color999999, for: .normal)
            $0.addTarget(self, action: #selector(recommendBtnClick), for: .touchUpInside)
        }
        view.addSubview(recommendBtn)
        
        let wrinkles_report = resultModel.acne_report
        self.addH5(str: wrinkles_report)
        let imgArray = self.resultModel.makeup//
        self.imgArr = imgArray.reversed()
        self.imgPreviewView.kf.setImage(with: URL(string: "\(self.imgArr.first ?? "")"))
    }
    
    
    private func addH5(str: String) {
        
        let htmlString = str//"<p>hello</p>"//"\(listModel.explain)"//
        guard let data = htmlString.data(using: .utf8) else {
            ShowHUD(str: "富文本解析失败")
            return
        }
        print(htmlString)
        
        
        if let attributedString = try? NSMutableAttributedString(data: data, options: [.documentType : NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) {
            explainL.attributedText = attributedString
            let height = attributedString.boundingRect(with: CGSize(width: scrollView.width - 120, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin]/*[.usesLineFragmentOrigin, .usesFontLeading]*/, context: nil).height
//            let size = attributedString.size()
            explainL.height = height + 20
            scrollView.contentSize = CGSize(width: scrollView.width, height: explainL.bottom + 10)
        } else {
            print("无效的HTML字符串")
        }
        
    }
    
    /// 获取美妆推荐信息
    private func getBeautyRecommend() {
        
        let param = [
            "event_name": event_name,
            "raw_file_path": raw_file_path
        ]
        
//        HUD.flash(.labeledProgress(title: "", subtitle: "数据获取中..."), delay: 60)
        let url = "http://124.222.206.164:3030/develop_facial_detection"
        QINetworkManager.requestJson(urlStr: url, parameters: param, isJson: true) { json in
//            print(json)
            let wuGuanModel = json.dictionaryObject?.kj.model(QIFiveSensesResultModel.self) ?? QIFiveSensesResultModel()
            self.beautyRecommendCtl.raw_file_path = self.raw_file_path
            self.beautyRecommendCtl.event_name = self.event_name
            self.beautyRecommendCtl.wuGuanModel = wuGuanModel
        }
        
    }
    
    /// 粉刺
    @objc private func acneBtnClick(btn: UIButton) {
        selectItemBtn.isSelected = false
        selectItemBtn.backgroundColor = ColorWithStr("#FFDCE0")
        btn.isSelected = true
        btn.backgroundColor = MainColor
        selectItemBtn = btn
        addH5(str: resultModel.acne_report)
        if imgArr.count > 0 {
            imgPreviewView.kf.setImage(with: URL(string: "\(self.imgArr.first ?? "")"))
        }
    }
    /// 毛孔
    @objc private func poreBtnClick(btn: UIButton) {
        selectItemBtn.isSelected = false
        selectItemBtn.backgroundColor = ColorWithStr("#FFDCE0")
        btn.isSelected = true
        btn.backgroundColor = MainColor
        selectItemBtn = btn
        addH5(str: resultModel.pores_report)
        if imgArr.count > 1 {
            imgPreviewView.kf.setImage(with: URL(string: "\(self.imgArr[1])"))
        }
    }
    /// 皱纹
    @objc private func wrinkleBtnClick(btn: UIButton) {
        selectItemBtn.isSelected = false
        selectItemBtn.backgroundColor = ColorWithStr("#FFDCE0")
        btn.isSelected = true
        btn.backgroundColor = MainColor
        selectItemBtn = btn
        addH5(str: resultModel.wrinkles_report)
        if imgArr.count > 2 {
            imgPreviewView.kf.setImage(with: URL(string: "\(self.imgArr.last ?? "")"))
        }
    }
    
    /// 相关产品
    @objc private func productsBtnClick() {
        let ctl = RelatedProductsViewController()
        ctl.resultModel = resultModel
        ctl.index = selectItemBtn.tag
        navigationController?.pushViewController(ctl, animated: true)
    }
    
    /// 美妆推荐
    @objc private func recommendBtnClick() {
        
        beautyRecommendCtl.previewImg = img
        beautyRecommendCtl.raw_file_path = raw_file_path
        beautyRecommendCtl.event_name = event_name
//        ctl.wuGuanModel = wuGuanModel
        beautyRecommendCtl.originalImgUrl = originalImgUrl
        navigationController?.pushViewController(beautyRecommendCtl, animated: true)
    }

}
